package com.imay.live.media;

import android.app.Service;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import com.imay.base.helper.NetworkHelper;
import com.imay.live.helper.ThreadManager;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayConfig;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ugc.TXRecordCommon;
import com.tencent.rtmp.ui.TXCloudVideoView;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by jeaman on 2017/4/20.
 */

public class LivePlayer implements ITXLivePlayListener {
    private static final int  CACHE_STRATEGY_FAST  = 1;  //极速
    private static final int  CACHE_STRATEGY_SMOOTH = 2;  //流畅
    private static final int  CACHE_STRATEGY_AUTO = 3;  //自动
    private static final int  CACHE_STRATEGY_LINK_MIC  = 4;  //连麦
    private static final float  CACHE_TIME_FAST = 1.0f;
    private static final float  CACHE_TIME_SMOOTH = 5.0f;
    private static final float  CACHE_TIME_LINK_MIC = 0.2f;

    private TXLivePlayer mLivePlayer;
    private TXLivePlayConfig mPlayConfig;
    private boolean mHWDecode = false;
    private int mPlayType = TXLivePlayer.PLAY_TYPE_LIVE_FLV;
    private int mCurrentRenderMode = TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN;  //填满屏幕
    private int mCurrentRenderRotation = TXLiveConstants.RENDER_ROTATION_PORTRAIT;
    private int mCacheStrategy = 0;

    private TXCloudVideoView mVideoView;
    private String mPlayUrl;

    private PlayListener mListener;

    private boolean mStartPlayLive; //是否开始播放http流地址
    private boolean mPause;
    private Timer mTimer;
    private TimerTask mReconnectTimerTask;
    private int mReconnectCount;

    private final PhoneStateListener listener = new PhoneStateListener(){
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            switch(state){
                //电话等待接听
                case TelephonyManager.CALL_STATE_RINGING:
                    pause();
                    break;
                //电话接听
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    pause();
                    break;
                //电话挂机
                case TelephonyManager.CALL_STATE_IDLE:
                    resume();
                    break;
            }
        }
    };

    public LivePlayer(Context context, TXCloudVideoView videoView) {
        //        mHWDecode = HWSupportList.isHWVideoEncodeSupport();
        mVideoView = videoView;
        mLivePlayer = new TXLivePlayer(context);
        mPlayConfig = new TXLivePlayConfig();
        mPlayConfig.setConnectRetryInterval(3);
        mPlayConfig.setConnectRetryCount(9);    //重试次数
        setCacheStrategy(CACHE_STRATEGY_AUTO);

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
        tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    public void pause() {
        mPause = true;
        if (mLivePlayer != null) {
            if (isLiveMode()) {
                stopPlay();
            } else {
                mLivePlayer.pause();
            }
        }
    }

    public void resume() {
        mPause = false;
        if (mLivePlayer != null) {
            if (isLiveMode()) {
                startPlay();
            } else {
                mLivePlayer.resume();
            }
        }
    }

    public void setMute(boolean mute) {
        if (mLivePlayer != null) {
            mLivePlayer.setMute(mute);
        }
    }

    public boolean startPlay() {
        return startPlay(this);
    }

    public boolean startPlay(ITXLivePlayListener listener) {
        cancelReconnect();
        if (mLivePlayer == null || mPlayUrl == null) {
            return false;
        }
        if (mLivePlayer.isPlaying()) {
            mLivePlayer.stopPlay(false);
        }
        mStartPlayLive = true;
//        //由于iOS AppStore要求新上架的app必须使用https,所以后续腾讯云的视频连接会支持https,但https会有一定的性能损耗,所以android将统一替换会http
//        if (playUrl.startsWith("https://")) {
//            playUrl = "http://" + playUrl.substring(8);
//        }

        mLivePlayer.setPlayerView(mVideoView);
        mLivePlayer.setPlayListener(listener);
        setPlayConfig();

        int result = mLivePlayer.startPlay(mPlayUrl, mPlayType); // result返回值：0 success;  -1 empty url; -2 invalid url; -3 invalid playType;
        if (result != 0) {
            return false;
        }
        return true;
    }

    public void stopPlay() {
        mStartPlayLive = false;
        if (mLivePlayer != null) {
            mLivePlayer.setPlayListener(null);
            mLivePlayer.stopPlay(true);
        }
    }

    public int startRecord(TXRecordCommon.ITXVideoRecordListener listener) {
        int result = -1;
        if (mLivePlayer != null) {
            mLivePlayer.setVideoRecordListener(listener);
            result = mLivePlayer.startRecord(TXRecordCommon.RECORD_TYPE_STREAM_SOURCE);
        }
        return result;
    }

    public void stopRecord() {
        if (mLivePlayer != null) {
            mLivePlayer.stopRecord();
        }
    }

    public void onDestroy() {
        stopPlay();
        if (mVideoView != null) {
            mVideoView.onDestroy();
        }
        if (mLivePlayer != null) {
            mLivePlayer.setPlayListener(null);
            mLivePlayer.setVideoRecordListener(null);
        }
    }

    private void setPlayUrl(String playUrl) {
        mPlayUrl = playUrl;
    }

//    //点播模式
//    public void setVodPlayMode(String playUrl) {
//        mPlayType = getVodPlayType(playUrl);
//    }
//
//    //连麦播放模式
//    public void setLinkMicPlayMode() {
//        mPlayType = TXLivePlayer.PLAY_TYPE_LIVE_RTMP_ACC;
//        setCacheStrategy(CACHE_STRATEGY_LINK_MIC);
//    }
//
//    //普通直播模式
//    public void setLivePlayMode() {
//        mPlayType = TXLivePlayer.PLAY_TYPE_LIVE_FLV;
//        setCacheStrategy(CACHE_STRATEGY_AUTO);
//    }

    //直播
    public void setLiveUrl(String playUrl) {
        setPlayUrl(playUrl);
        mPlayType = TXLivePlayer.PLAY_TYPE_LIVE_FLV;
        setCacheStrategy(CACHE_STRATEGY_AUTO);
    }

    //连麦
    public void setLinkMicUrl(String playUrl) {
        setPlayUrl(playUrl);
        mPlayType = TXLivePlayer.PLAY_TYPE_LIVE_RTMP_ACC;
        setCacheStrategy(CACHE_STRATEGY_LINK_MIC);
    }

    //本地文件
    public void setLocalUrl(String playUrl) {
        setPlayUrl(playUrl);
        mPlayType = TXLivePlayer.PLAY_TYPE_LOCAL_VIDEO;
    }

    //点播
    public void setVodUrl(String playUrl) {
        setPlayUrl(playUrl);
        mPlayType = getVodPlayType(playUrl);
    }

    private int getVodPlayType(String playUrl) {
        if (playUrl.startsWith("http://") || playUrl.startsWith("https://")) {
            if (playUrl.contains(".flv")) {
                return TXLivePlayer.PLAY_TYPE_VOD_FLV;
            } else if (playUrl.contains(".m3u8")) {
                return TXLivePlayer.PLAY_TYPE_VOD_HLS;
            } else if (playUrl.toLowerCase().contains(".mp4")) {
                return TXLivePlayer.PLAY_TYPE_VOD_MP4;
            }
        }
        return TXLivePlayer.PLAY_TYPE_VOD_MP4;
    }

    private boolean isLiveMode() {
        return mPlayType == TXLivePlayer.PLAY_TYPE_LIVE_RTMP || mPlayType == TXLivePlayer.PLAY_TYPE_LIVE_FLV || mPlayType == TXLivePlayer.PLAY_TYPE_LIVE_RTMP_ACC;
    }

    //缓存策略
    private void setCacheStrategy(int nCacheStrategy) {
        if (mLivePlayer == null || mCacheStrategy == nCacheStrategy) {
            return;
        }
        mCacheStrategy = nCacheStrategy;

        switch (nCacheStrategy) {
            case CACHE_STRATEGY_FAST:
                mPlayConfig.setAutoAdjustCacheTime(true);
                mPlayConfig.setMaxAutoAdjustCacheTime(CACHE_TIME_FAST);
                mPlayConfig.setMinAutoAdjustCacheTime(CACHE_TIME_FAST);
                mLivePlayer.setConfig(mPlayConfig);
                break;

            case CACHE_STRATEGY_SMOOTH:
                mPlayConfig.setAutoAdjustCacheTime(false);
                mPlayConfig.setCacheTime(CACHE_TIME_SMOOTH);
                mLivePlayer.setConfig(mPlayConfig);
                break;

            case CACHE_STRATEGY_AUTO:
                mPlayConfig.setAutoAdjustCacheTime(true);
                mPlayConfig.setMaxAutoAdjustCacheTime(CACHE_TIME_SMOOTH);
                mPlayConfig.setMinAutoAdjustCacheTime(CACHE_TIME_FAST);
                mLivePlayer.setConfig(mPlayConfig);
                break;
            case CACHE_STRATEGY_LINK_MIC:
                mPlayConfig.setAutoAdjustCacheTime(true);
                mPlayConfig.setMaxAutoAdjustCacheTime(CACHE_TIME_LINK_MIC);
                mPlayConfig.setMinAutoAdjustCacheTime(CACHE_TIME_LINK_MIC);
                mLivePlayer.setConfig(mPlayConfig);
            default:
                break;
        }
    }

    private void setPlayConfig() {
        // 硬件加速在1080p解码场景下效果显著，但细节之处并不如想象的那么美好：
        // (1) 只有 4.3 以上android系统才支持
        // (2) 兼容性我们目前还仅过了小米华为等常见机型，故这里的返回值您先不要太当真
        mLivePlayer.enableHardwareDecode(mHWDecode);
        mLivePlayer.setRenderRotation(mCurrentRenderRotation);
        mLivePlayer.setRenderMode(mCurrentRenderMode);
        //设置播放器缓存策略
        //这里将播放器的策略设置为自动调整，调整的范围设定为1到4s，您也可以通过setCacheTime将播放器策略设置为采用
        //固定缓存时间。如果您什么都不调用，播放器将采用默认的策略（默认策略为自动调整，调整范围为1到4s）
        //mLivePlayer.setCacheTime(5);
        mLivePlayer.setConfig(mPlayConfig);
    }

    @Override
    public void onPlayEvent(int event, Bundle param) {
        if (event == TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME) {
            mReconnectCount = 0;
            if (mListener != null) {
                mListener.onPlayBegin();
            }
        } else if (event == TXLiveConstants.PLAY_ERR_NET_DISCONNECT || event == TXLiveConstants.PLAY_ERR_GET_RTMP_ACC_URL_FAIL) {
            //设置了超大重试次数，基本不会出现连接断开的状态
            if (mListener != null) {
                mListener.onPlayError();
            }
            tryReconnect();
        } else if (event == TXLiveConstants.PLAY_WARNING_RECONNECT) {
            mReconnectCount++;
            if (mListener != null) {
                mListener.onPlayReconnect(mReconnectCount);
            }
        } else if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {
            if (mListener != null) {
                mListener.onPlayEnd();
            }
        } else if (event == TXLiveConstants.PLAY_EVT_PLAY_PROGRESS) {
            int progress = param.getInt(TXLiveConstants.EVT_PLAY_PROGRESS);
            int duration = param.getInt(TXLiveConstants.EVT_PLAY_DURATION);
            if (mListener != null) {
                mListener.onPlayProgress(progress, duration);
            }
        }
    }

    @Override
    public void onNetStatus(Bundle bundle) {

    }

    private boolean needReconnect() {
        if (!mStartPlayLive || mPause || !NetworkHelper.getInstance().hasConnection()) {
            return false;
        }
        return true;
    }

    //尝试重连
    private void tryReconnect() {
        cancelReconnect();
        mReconnectTimerTask = new TimerTask() {
            @Override
            public void run() {
                ThreadManager.post(new Runnable() {
                    @Override
                    public void run() {
                        if (needReconnect()) {
                            startPlay();
                        }
                    }
                });
            }
        };
        if (mTimer == null) {
            mTimer = new Timer();
        }
        mTimer.schedule(mReconnectTimerTask, 3000, 3000);
    }

    private void cancelReconnect() {
        if (mReconnectTimerTask != null) {
            mReconnectTimerTask.cancel();
        }
    }

    public void setPlayListener(PlayListener listener) {
        this.mListener = listener;
    }

    public interface PlayListener {
        void onPlayBegin();
        void onPlayEnd();
        void onPlayReconnect(int count);
        void onPlayError();
        void onPlayProgress(int progress, int duration);
    }
}
